package com.farm.authority.service.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.farm.parameter.FarmParameterService;
import com.farm.util.cache.FarmCacheName;
import com.farm.util.cache.FarmCaches;
import com.farm.web.constant.FarmConstant;

/**
 * 当前用户信息，用来控制用户重复登陆
 * 
 * @author macpl
 *
 */
public class CurrentUserUtils {

	public static void userLoginHandle(String userid, String sessionId) {
		if (!FarmParameterService.getInstance().getParameterBoolean("config.sys.login.manyuser")) {
			if (StringUtils.isNotBlank(userid) && StringUtils.isNotBlank(sessionId)) {
				FarmCaches.getInstance().putCacheData(userid, sessionId, FarmCacheName.wcpLoginCurrentuser);
			}
		}
	}

	public static void checkValidatHandle(String userid, HttpSession httpSession, HttpServletRequest request) {
		if (!FarmParameterService.getInstance().getParameterBoolean("config.sys.login.manyuser")) {
			String rsessionid = (String) FarmCaches.getInstance().getCacheData(userid,
					FarmCacheName.wcpLoginCurrentuser);
			// 如果当前用户sessionid和记录的sessionid符合，则报错
			if (StringUtils.isNotBlank(rsessionid) && httpSession != null && !rsessionid.equals(httpSession.getId())) {
				httpSession.setAttribute(FarmConstant.SESSION_USEROBJ, null);
				String message = "当前账号已在异地登录";
				request.setAttribute("MESSAGE", message);
				throw new RuntimeException(message);
			}
		}
	}
}
